package fatboy.addons;

import java.io.Serializable;

import fatboy.communication.ObjectID;

/**
 * Listener Class is a class to wait for other nodes to give acknowledgements
 * @author Jack
 * 
 */
public class Listener implements Serializable {
	private int done;
	private int soFar;
	private int myCount;
	private ObjectID here;
	private Listener caller;
	/**
	 * a constructor to make the remote proxy for this class work
	 */
	public Listener(){
		//exist
	}
	
	/**
	 * Constructor for basic use, but not the starting use see fatboy.addon.FinalListener
	 * takes how many things this should wait for to answer, and what it should report to 
	 * @param size the number of listener objects that this listener is listening for
	 * @param caller the Listener this should report to onceall have answered
	 * @pre true
	 * @post new listener listening for size number of things if that is zero it 
	 * will already have reported to the listener above it
	 */
	public Listener(int size, Listener caller) {
		here = new ObjectID();
		done = size;
		soFar = -1;
		myCount = 0;
		this.caller = caller;
		inc(1);
	}
	/**
	 * Method to cause a listener to count that one of the lower listeners has reported
	 * and will report to the higher listener if all have reported
	 * @pre a listener this is listening to has just reported all acknowledged
	 * @post number of things reporting one greater and will report to the higher listener
	 * if it has received acknowledgments from all the listeners below it 
	 */
	public void inc(int count){
		soFar++;
		myCount+= count;
		if(done == soFar){
			caller.inc(myCount);
		}
		
	}
	public Object writeReplace(){
		return new ProxyListener(this.getId());
	}
	protected ObjectID getId() {
		return here;
	}
}
